package com.lwq.weatherapp.data;

import com.lwq.weatherapp.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.RecycleItemProvider;

import java.util.ArrayList;

/**
 *  列表项
 */
public class ListItemProvider extends RecycleItemProvider {

    private AbilitySlice mSlice;
    private OnItemClickListener listener;
    private ArrayList<DataMo> dataMos = new ArrayList<>();
    public ListItemProvider(AbilitySlice abilitySlice, OnItemClickListener listener) {
        this.mSlice = abilitySlice;
        this.listener = listener;
    }
    public void setData(ArrayList<CityMo> cityMos){
        dataMos.clear();
        int i = 0;
        ArrayList<CityMo> tempList = new ArrayList<>();
        for (CityMo mo: cityMos) {
            if (i == 3) {
                i = 0;
                dataMos.add(new DataMo(tempList));
                tempList = new ArrayList<>();
            }
            tempList.add(mo);
            i++;
        }
        dataMos.add(new DataMo(tempList));
        this.notifyDataChanged();//调用此方法刷新数据
    }

    @Override
    public int getCount() {
        return dataMos.size();
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    public Object getItem(int i) {
        return null;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        Component component1 = LayoutScatter.getInstance(mSlice).parse(ResourceTable.Layout_list_item, null, false);
        if (!(component1 instanceof ComponentContainer)) {
            return null;
        }
        ComponentContainer rootLayout = (ComponentContainer) component1;
        DataMo dataMo = dataMos.get(i);
        for (CityMo mo: dataMo.cityMos) {
            Text titleItem = (Text) LayoutScatter.getInstance(mSlice).parse(ResourceTable.Layout_item_title, null, false);
            titleItem.setText(mo.cityName);
            rootLayout.addComponent(titleItem);
            titleItem.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    listener.onItemClick(mo, i);
                }
            });
        }
        return component1;
    }

    //点击监听
    public interface OnItemClickListener {
        //城市模型,位置
        void onItemClick(CityMo mo, int position);
    }

}
